﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceModel;
using System.Text;
using Raspare;
using Xamarin.Forms;

namespace SharedMobilePlatform
{
	public class SelectPage : RaspContentPage
	{
	    public ProgressBar progressBar;

	    public List<string> dekaederCharacters = null;

	    private ListView listView;

        protected override bool OnBackButtonPressed()
        {
            Application.Current.Properties["ListOfCharacter"] = null;
            Application.Current.Properties["Character"] = null;

            return base.OnBackButtonPressed();
        }

        public SelectPage(string raspnamn)
        {
            dekaederCharacters = new List<string>();

            if (Application.Current.Properties.ContainsKey("ListOfCharacter") && Application.Current.Properties["ListOfCharacter"] != null)
            {
                dekaederCharacters = ((string) Application.Current.Properties["ListOfCharacter"]).Split(';').ToList();
            }
            
            Debug.WriteLine(String.Join(";", dekaederCharacters));

            //Debug
            //dekaederCharacters = new List<string>() { "Olof Löfquist", "John Richter" };
            
            progressBar = new ProgressBar()
            {
                Progress = 0.2
            };
            
            progressBar.ProgressTo(.8, 30000, Easing.Linear);

            listView = new Xamarin.Forms.ListView()
            {
                RowHeight = 40,
                ItemsSource = dekaederCharacters,
                
            };

		    listView.ItemTapped += showMessage;

			Content = new StackLayout {
				Children = {
                    progressBar,
					listView
				}
			};

            if (dekaederCharacters != null && dekaederCharacters.Any())
            {
                if (Application.Current.Properties.ContainsKey("Character") && Application.Current.Properties["Character"] != null)
                {
                    progressBar.IsVisible = false;
                    Karaktär Character = new Karaktär();
                    System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(Character.GetType());
                    using (StringReader textReader = new StringReader((string)Application.Current.Properties["Character"]))
                    {
                        Character = (Karaktär)x.Deserialize(textReader);
                        Navigation.PushAsync(new ShowCharacterPage(Character));
                    }
                }
            }else
            {
                _client.GetMyDekaederCharacterListAsync(raspnamn);
            }
		}
        
        public override void InitializeWcfServiceClient()
        {
            _client.GetMyDekaederCharacterListCompleted += UpdateCharacters;
        }

        private void UpdateCharacters(object sender, GetMyDekaederCharacterListCompletedEventArgs e)
        {
            Debug.WriteLine("UpdatingCharacters Async");

            Device.BeginInvokeOnMainThread(() =>
            {
                Debug.WriteLine("Inside MainThread");
                progressBar.IsVisible = false;
                if (!e.Cancelled)
                {
                    Debug.WriteLine("Setting Characters");
                    dekaederCharacters = e.Result.ToList();
                    Debug.WriteLine("Characters" + String.Join(";", dekaederCharacters));
                    Application.Current.Properties["ListOfCharacter"] = String.Join(";", dekaederCharacters);
                    listView.ItemsSource = dekaederCharacters;
                }
            });
            
        }

        public void showMessage(object sender, ItemTappedEventArgs args)
	    {
            if (args != null && !String.IsNullOrWhiteSpace(args.Item.ToString()))
            {
                Navigation.PushAsync(new ShowCharacterPage(args.Item.ToString()));
            }
	    }

	}
}
